package com.example.weight.wormHandle.garbageDisposal.researchDevelopment;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Adapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.arrayAdapter.Item;
import com.example.weight.arrayAdapter.ItemAdapter;
import com.example.weight.config.Config;
import com.example.weight.greenSeasons.researchDevelopment.IncomingScene;
import com.example.weight.util.WeightActivity;
import com.example.weight.wormHandle.cultivate.HatchingOutcoming;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

public class IncomingSceneCrush extends AppCompatActivity implements View.OnClickListener{
    private String name, batchStr, factory;
    private TitleBar titleBar;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
    Date incomingDate = new Date(System.currentTimeMillis());
    private TextView feed_date;
    Map<String, Integer> materialMap = new HashMap<String,Integer>();
    private SharedPreferences preferences;
    private ItemAdapter batchAdapter;
    private ItemAdapter groupAdapter;
    private ItemAdapter materialAdapter;
    private List<String> batchList;
    private List<String> groupList;
    private List<String> materialList;
    private EditText batch;
    private EditText group;
    private EditText boxNumber;
    private PopupWindow batchPopupWindow;
    private PopupWindow groupPopupWindow;
    private PopupWindow materialPopupWindow;

    private TextView deviceName_1;
    private TextView crush_start;
    private TextView crush_end;
    private Button btn_crush_start;
    private Button btn_crush_end;
    private EditText incoming_scene_material;
    private EditText crush_material_weight;
    private EditText remark;

    private String device;

    String activeButton = new String();
    Calendar calendar= Calendar.getInstance(Locale.CHINA);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");
        Log.d("crush0",factory);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.incoming_scene_crush);

        titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                IncomingSceneCrush.this.finish();
            }

            @Override
            public void onTitleClick(View v) {
            }
            @Override
            public void onRightClick(View v) {
            }
        });
        /**
         * 显示设置日期
         */
        feed_date = findViewById(R.id.incoming_scene_feedDate);
        feed_date.setText(simpleDateFormat.format(incomingDate));

        deviceName_1 = findViewById(R.id.incoming_scene_deviceName_1);
        crush_start = (TextView) findViewById(R.id.crush_start);
        crush_start.setOnClickListener(this);
        crush_end = (TextView) findViewById(R.id.crush_end);
        crush_end.setOnClickListener(this);

        btn_crush_start = findViewById(R.id.btn_crush_start);
        btn_crush_end = findViewById(R.id.btn_crush_end);
        btn_crush_start.setOnClickListener(this);
        btn_crush_end.setOnClickListener(this);
        incoming_scene_material = findViewById(R.id.incoming_scene_material);
        materialMap.put("易腐物",0);
        materialMap.put("厨余",1);
        materialMap.put("餐厨",2);
        //粉碎物料重量
        crush_material_weight = findViewById(R.id.crush_material_weight);

        remark = findViewById(R.id.incoming_scene_remark);
        device = "书柜" + deviceName_1.getText().toString();
        /**
         *两个输入记录缓存
         */
        batch = findViewById(R.id.incoming_scene_batch);
        group = findViewById(R.id.incoming_scene_group);
        boxNumber = findViewById(R.id.incoming_scene_number);
        preferences = getSharedPreferences("incoming_scene", Context.MODE_PRIVATE);
        batchList = new ArrayList<>(preferences.getStringSet("batchList", new HashSet<>()));
        groupList = new ArrayList<>(preferences.getStringSet("groupList", new HashSet<>()));
        materialList = new ArrayList<>(preferences.getStringSet("materialList",new HashSet<>()));

        List<Item> batchItemList = new ArrayList<>();
        List<Item> groupItemList = new ArrayList<>();
        List<Item> materialItemList = new ArrayList<>();

        // Item类型list初始化
        for (String itemName : batchList) {
            batchItemList.add(new Item(itemName, R.drawable.ic_clear));
        }
        for (String itemName : groupList) {
            groupItemList.add(new Item(itemName, R.drawable.ic_clear));
        }
        for (String itemName : materialList) {
            materialItemList.add(new Item(itemName, R.drawable.ic_clear));
        }

        // 创建ListView
        batchAdapter = new ItemAdapter(this, R.layout.adapter_item, batchItemList);
        groupAdapter = new ItemAdapter(this, R.layout.adapter_item, groupItemList);
        materialAdapter = new ItemAdapter(this,R.layout.adapter_item,materialItemList);
        ListView batchListView = new ListView(this);
        batchListView.setAdapter(batchAdapter);
        batchListView.setOnItemClickListener((parent, view, position, id) -> {
            // 若有进行删除操作，更新nameList，否则nameList序号对不上
            if (batchAdapter.getDeletePos() >= 0) {
                List<Item> tempItemList = batchAdapter.getList();
                batchList.clear();
                for (Item item : tempItemList) {
                    batchList.add(item.getName());
                }
            }
            // 根据所选设置输入框文本
            String result = batchList.get(position);
            batch.setText(result);
            batchPopupWindow.dismiss();
            hideInput();
        });

        ListView groupListView = new ListView(this);
        groupListView.setAdapter(groupAdapter);
        groupListView.setOnItemClickListener((parent, view, position, id) -> {
            // 若有进行删除操作，更新nameList，否则nameList序号对不上
            if (groupAdapter.getDeletePos() >= 0) {
                List<Item> tempItemList = groupAdapter.getList();
                groupList.clear();
                for (Item item : tempItemList) {
                    groupList.add(item.getName());
                }
            }
            // 根据所选设置输入框文本
            String result = groupList.get(position);
            group.setText(result);
            groupPopupWindow.dismiss();
            hideInput();
        });

        ListView materialListView = new ListView(this);
        materialListView.setAdapter(materialAdapter);
        materialListView.setOnItemClickListener((parent, view, position, id) -> {
            // 若有进行删除操作，更新nameList，否则nameList序号对不上
            if (materialAdapter.getDeletePos() >= 0) {
                List<Item> tempItemList = materialAdapter.getList();
                materialList.clear();
                for (Item item : tempItemList) {
                    materialList.add(item.getName());
                }
            }
            // 根据所选设置输入框文本
            String result = materialList.get(position);
            incoming_scene_material.setText(result);
            materialPopupWindow.dismiss();
            hideInput();
        });


        // 获取屏幕的宽度并设置popupwindow的宽度为width,这里是根据布局控件所占的权重
        WindowManager wManager = (WindowManager) getSystemService(this.WINDOW_SERVICE);
        int width = wManager.getDefaultDisplay().getWidth() * 3 / 5;
        int height = wManager.getDefaultDisplay().getHeight() / 8;
        // 参数为 1.View 2.宽度 3.高度
        batchPopupWindow = new PopupWindow(batchListView ,width, height);
        // 设置点击外部区域可以取消popupWindow
        batchPopupWindow.setOutsideTouchable(true);

        batch.setOnFocusChangeListener((v, hasFocus) -> {
            // 设置popupWindow显示,并且告诉它显示在那个View下面
            if (hasFocus) {
                // 若聚焦到该输入框，显示下拉列表
                batchPopupWindow.showAsDropDown(batch);
            }
        });

        groupPopupWindow = new PopupWindow(groupListView ,width, height);
        // 设置点击外部区域可以取消popupWindow
        groupPopupWindow.setOutsideTouchable(true);

        group.setOnFocusChangeListener((v, hasFocus) -> {
            // 设置popupWindow显示,并且告诉它显示在那个View下面
            if (hasFocus) {
                // 若聚焦到该输入框，显示下拉列表
                groupPopupWindow.showAsDropDown(group);
            }
        });

        materialPopupWindow = new PopupWindow(materialListView ,width, height);
        // 设置点击外部区域可以取消popupWindow
        materialPopupWindow.setOutsideTouchable(true);

        incoming_scene_material.setOnFocusChangeListener((v, hasFocus) -> {
            // 设置popupWindow显示,并且告诉它显示在那个View下面
            if (hasFocus) {
                // 若聚焦到该输入框，显示下拉列表
                materialPopupWindow.showAsDropDown(incoming_scene_material);
            }
        });

    }
    /**
     * 提交内容并设置输入缓存
     * @param view
     */
    public void save(View view) {
        if (crush_start.getText().toString().equals("")) {
            Toast.makeText(this, "请填写粉碎开始时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (crush_end.getText().toString().equals("")) {
            Toast.makeText(this, "请填写粉碎结束时间", Toast.LENGTH_SHORT).show();
            return;
        }if (((TextView) findViewById(R.id.incoming_scene_deviceName_1)).getText().toString().equals("")) {
            Toast.makeText(this, "请填写设备名称", Toast.LENGTH_SHORT).show();
            return;
        }if ( ((TextView) findViewById(R.id.incoming_scene_batch)).getText().toString().equals("")) {
            Toast.makeText(this, "请填写批次", Toast.LENGTH_SHORT).show();
            return;
        }if (((TextView) findViewById(R.id.incoming_scene_group)).getText().toString().equals("")) {
            Toast.makeText(this, "请填写组别", Toast.LENGTH_SHORT).show();
            return;
        }if (((TextView) findViewById(R.id.incoming_scene_number)).getText().toString().equals("")) {
            Toast.makeText(this, "请填写编号", Toast.LENGTH_SHORT).show();
            return;
        }if (((TextView) findViewById(R.id.incoming_scene_number)).getText().toString().equals("")) {
            Toast.makeText(this, "请填写物料名称", Toast.LENGTH_SHORT).show();
            return;
        }if (crush_material_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写粉碎物料重量", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {
                    //输入缓存
                    SharedPreferences.Editor editor = preferences.edit();
                    // 若有进行删除操作，更新batchList
                    List<Item> tempBatchList = batchAdapter.getList();
                    if (tempBatchList.size() != batchList.size()) {
                        batchList.clear();
                        for (Item item : tempBatchList) {
                            batchList.add(item.getName());
                        }
                    }
                    // 判断该输入框内容是否已存在，不存在则加入
                    String currentBatch = batch.getText().toString();
                    if (!currentBatch.equals("") && !batchList.contains(currentBatch)) {
                        batchList.add(currentBatch);
                    }

                    //若有进行删除操作，更新groupList
                    List<Item> tempGroupList = groupAdapter.getList();
                    if (tempGroupList.size() != groupList.size()) {
                        groupList.clear();
                        for (Item item : tempGroupList) {
                            groupList.add(item.getName());
                        }
                    }
                    // 判断该输入框内容是否已存在，不存在则加入
                    String currentGroup = group.getText().toString();
                    if (!currentGroup.equals("") && !groupList.contains(currentGroup)) {
                        groupList.add(currentGroup);
                    }

                    //若有进行删除操作，更新List
                    List<Item> tempMaterialList = materialAdapter.getList();
                    if (tempMaterialList.size() != materialList.size()) {
                        materialList.clear();
                        for (Item item : tempMaterialList) {
                            materialList.add(item.getName());
                        }
                    }
                    // 判断该输入框内容是否已存在，不存在则加入
                    String currentMaterial = incoming_scene_material.getText().toString();
                    if (!currentMaterial.equals("") && !materialList.contains(currentMaterial)) {
                        materialList.add(currentMaterial);
                    }

                    editor.putStringSet("batchList", new HashSet<>(batchList));
                    editor.putStringSet("groupList", new HashSet<>(groupList));
                    editor.putStringSet("materialList", new HashSet<>(materialList));
                    editor.apply();
                    batchStr = "S" + batch.getText().toString();
                    Log.d("+1", batchStr);

                    //提交请求
                    incomingDate = new Date(System.currentTimeMillis());
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/research/crush/add";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Log.d("jy", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        String flag = jsonObject.getString("data");
                                        Log.d("flag", String.valueOf(flag.equals("已保存过是否仍需保存")));
                                        if (code.startsWith("2")&&!flag.equals("已保存过是否仍需保存")){
                                            Toast.makeText(IncomingSceneCrush.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        }else if(flag.equals("已保存过是否仍需保存")){

                                            new AlertDialog.Builder(IncomingSceneCrush.this)
                                                    .setTitle("已保存过是否仍需保存？")
                                                    .setCancelable(false)
                                                    .setNegativeButton("取消", ((dialog, which) ->
                                                            Toast.makeText(IncomingSceneCrush.this, "取消保存", Toast.LENGTH_SHORT).show()))
                                                    .setPositiveButton("确定", (dialog, which) -> {
                                                        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                                                                new Response.Listener<String>() {
                                                                    @Override
                                                                    public void onResponse(String response) {
                                                                        Log.d("jy", response);
                                                                        try {
                                                                            JSONObject jsonObject = new JSONObject(response);
                                                                            String code = jsonObject.getString("code");
                                                                            if (code.startsWith("2"))
                                                                                Toast.makeText(IncomingSceneCrush.this,
                                                                                        "保存成功", Toast.LENGTH_SHORT).show();
                                                                            else{
                                                                                Toast.makeText(IncomingSceneCrush.this,
                                                                                        "保存失败", Toast.LENGTH_SHORT).show();
                                                                            }
                                                                        } catch (JSONException e) {
                                                                            e.printStackTrace();
                                                                        }
                                                                    }
                                                                }, new Response.ErrorListener() {
                                                            @Override
                                                            public void onErrorResponse(VolleyError error) {
                                                                Toast.makeText(IncomingSceneCrush.this, "保存失败", Toast.LENGTH_SHORT).show();
                                                                Log.d("jy", error.toString());
                                                            }
                                                        }) {
                                                            @Override
                                                            protected Map<String, String> getParams() throws AuthFailureError {
                                                                Map<String, String> map=new HashMap<>();

                                                                Log.d("device设备名", device);
                                                                map.put("save", "1");
                                                                map.put("feedDate", simpleDateFormat.format(incomingDate));
                                                                map.put("crushStarttime", crush_start.getText().toString());
                                                                map.put("crushEndtime", crush_end.getText().toString());
                                                                map.put("deviceName1", device);
                                                                map.put("batch", "S" + batchStr);
                                                                map.put("zubie", group.getText().toString());
                                                                map.put("boxNumber", boxNumber.getText().toString());
                                                                map.put("incomingSceneMaterial", incoming_scene_material.getText().toString());
                                                                map.put("crushMaterialWeight", crush_material_weight.getText().toString());
                                                                map.put("remark", remark.getText().toString());
                                                                map.put("recorder",name);
                                                                map.put("factory",factory);
                                                                return map;
                                                            }
                                                        };
                                                        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                                                                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                                                        queue.add(stringRequest);
                                                    })
                                                    .show();
                                        }
                                        else{
                                            Toast.makeText(IncomingSceneCrush.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(IncomingSceneCrush.this, "保存失败", Toast.LENGTH_SHORT).show();
                            Log.d("jy", error.toString());
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("save", "0");
                            map.put("feedDate", simpleDateFormat.format(incomingDate));
                            map.put("crushStarttime", crush_start.getText().toString());
                            map.put("crushEndtime", crush_end.getText().toString());
                            map.put("deviceName1", "书柜"+deviceName_1.getText().toString());
                            map.put("batch", "S"+batch.getText().toString());
                            map.put("zubie", group.getText().toString());
                            map.put("boxNumber", boxNumber.getText().toString());
                            map.put("incomingSceneMaterial", incoming_scene_material.getText().toString());
                            map.put("crushMaterialWeight", crush_material_weight.getText().toString());
                            map.put("remark", remark.getText().toString());
                            map.put("recorder",name);
                            Log.d("crush",factory);
                            map.put("factory",factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }

    /**
     * 隐藏键盘
     */
    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    /**
     * 时间选择
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public static void showTimePickerDialog(Activity activity, int themeResId, final TextView tv, Calendar calendar) {
        // Calendar c = Calendar.getInstance();
        // 创建一个TimePickerDialog实例，并把它显示出来
        // 解释一哈，Activity是context的子类
        new TimePickerDialog( activity,themeResId,
                // 绑定监听器
                new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        tv.setText(String.format("%02d", hourOfDay) + ":" + String.format("%02d", minute));
                    }
                }
                // 设置初始时间
                , calendar.get(Calendar.HOUR_OF_DAY)
                , calendar.get(Calendar.MINUTE)
                // true表示采用24小时制
                ,true).show();
    }
    @Override
    public void onClick(View view) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
        switch (view.getId()) {
            case R.id.btn_crush_start:
                Date date_1_start = new Date(System.currentTimeMillis());
                String s_1_start = simpleDateFormat.format(date_1_start);
                crush_start.setText(s_1_start);
                btn_crush_start.setEnabled(false);
                break;
            case R.id.btn_crush_end:
                Date date_1_end = new Date(System.currentTimeMillis());
                String s_1_end = simpleDateFormat.format(date_1_end);
                crush_end.setText(s_1_end);
                btn_crush_end.setEnabled(false);
                break;
            case R.id.crush_start:
                showTimePickerDialog(this,  2, crush_start, calendar);
                break;
            case R.id.crush_end:
                showTimePickerDialog(this,  2, crush_end, calendar);;
                break;
            default:
                break;
        }
    }

    /**
     * 称重接口
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String weight = data.getStringExtra("weight");
        crush_material_weight.setText(weight);
    }
    public void goWeight(View view) {
        Intent intent = new Intent(IncomingSceneCrush.this, WeightActivity.class);
        startActivityForResult(intent, 1);
    }
}